package com.itstherules.jmsunit;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.TextMessage;

import com.itstherules.jmsunit.JmsCleaner;
import com.itstherules.jmsunit.JmsReceiver;
import com.itstherules.jmsunit.JmsSender;
import com.itstherules.jmsunit.header.HeadersPopulator;
import com.itstherules.jmsunit.headers.JmsHeadersDefinition;
import com.itstherules.jmsunit.managers.QueueManager;
import com.itstherules.jmsunit.util.HeadersCopier;

public final class JmsClient implements JmsSender, JmsReceiver, JmsCleaner {

	private final QueueManager manager;
	private final String queue;

	public JmsClient(QueueManager manager, String queue) throws JMSException {
		this.manager = manager;
		this.queue = queue;
	}
	
	public void send(String message, JmsHeadersDefinition jmsHeader) throws Exception {
		TextMessage textMessage = manager.getTextMessage(message);
		new HeadersPopulator(manager).populate(jmsHeader, textMessage);
		send(textMessage);
	}


	public final void send(TextMessage message) throws JMSException {
		QueueSender sender = null;
		try {
			sender = manager.getQueueSender(queue);
			TextMessage toSend = manager.createTextMessage(message.getText());
			new HeadersCopier().copyMessageHeaders(toSend, message);
			sender.send(toSend);
		} finally {
			if (sender != null) {
				sender.close();
			}
		}
	}
	
	public final void clean() throws JMSException {
		while (true) {
			Message received = receive(100);
			if (received == null) {
				break;
			}
		}
	}

	public final Message receive(long timeout) throws JMSException {
		QueueReceiver receiver = manager.getQueueReceiver(queue);
		return receiver.receive(timeout);
	}
	
	public Message receive(long timeout, String messageId) throws JMSException {
		MessageConsumer receiver = manager.getMessageConsumerWithMessageID(queue, messageId);
		return receiver.receive(timeout);
	}
}
